import React, { useState, useContext, useEffect } from "react";
import { FaDonate, FaPoll, FaVoteYea, FaCoins } from "react-icons/fa";
import { Link } from "react-router-dom";
import { AppState } from "../App";
import { ethers } from "ethers";
import "../css/mainStyles.css";
import "../css/loader.css";

const Main = () => {
  const App = useContext(AppState);

  const [amount, setAmount] = useState("");
  const [loading, setLoading] = useState(false);
  const [topContributors, setTopContributors] = useState([]);
  const [topProjects, setTopProjects] = useState([]);
  const [isLeaderboardVisible, setIsLeaderboardVisible] = useState(false);
  const [isProjectsVisible, setProjectsVisible] = useState(false);

  const toggleLeader = () => {
    setIsLeaderboardVisible(!isLeaderboardVisible);
  };

  const toggleProjects = () => {
    setProjectsVisible(!isProjectsVisible);
  };

  const Contribute = async () => {
    try {
      setLoading(true);
      const tx = await App.Foundationcontract.sendMoney({
        value: ethers.utils.parseUnits(amount, 0),
      });
      const transactionHash = tx.hash;
      await tx.wait();
      alert(`捐赠成功! 交易哈希: ${transactionHash}`);
      setAmount("");
      fetchTopContributors();
      fetchTopProjects();
    } catch (error) {
      console.error(error);
      alert("捐款金额不足100wei,捐赠失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchTopContributors = async () => {
    try {
      const maxTopContributors = 10; // 最多显示的贡献者数量
      const totalContributors =
        await App.Foundationcontract.contributorsNumber();
      const topN = Math.min(maxTopContributors, totalContributors); // 确保不超过最大数量
      const [addresses, contributions] =
        await App.Foundationcontract.getTopContributors(topN);
      const contributors = addresses.map((address, index) => ({
        address,
        amount: ethers.utils.formatUnits(contributions[index], 0),
      }));
      setTopContributors(contributors);
    } catch (error) {
      console.error("Error fetching top contributors:", error);
      // 处理错误
    }
  };

  const fetchTopProjects = async () => {
    try {
      const maxTopProjects = 10; // 最多显示的项目数量
      const totalProjects = await App.Foundationcontract.requestsNumber();
      const topN = Math.min(maxTopProjects, totalProjects); // 确保不超过最大数量
      const projects = await App.Foundationcontract.getTopVotedRequests(topN);
      const projectDetails = projects.slice(0, topN).map((project) => ({
        id: project.uniqueid,
        description: project.description,
        votes: project.votersNumber.toString(),
      }));
      setTopProjects(projectDetails);
    } catch (error) {
      console.error("Error fetching top projects:", error);
      // 处理错误
    }
  };

  useEffect(() => {
    fetchTopContributors();
    fetchTopProjects();
  }, []);

  return (
    <div className="main-container">
      {loading && <div className="loader"></div>}
      <div className="flex-container">
        <div className="hidden_left">
          <div className="hidden_icon" onClick={toggleLeader}>
            <FaCoins className="icon-white" />
            <span className="hover-text1">捐款金额排行榜</span>
          </div>
          <div className="hidden_icon" onClick={toggleProjects}>
            <FaPoll className="icon-white" />
            <span className="hover-text2">投票数量排行榜</span>
          </div>
        </div>
        <section
          className="leaderboard-section"
          style={{ display: isLeaderboardVisible ? "block" : "none" }}
        >
          <div className="leaderboard-title">捐款金额排行榜</div>
          <ul className="leaderboard-list">
            {topContributors.map((contributor, index) => (
              <li key={index} className="leaderboard-item">
                <span className="contributor-address">
                  {contributor.address}
                </span>
                :<span className="bold-amount">{contributor.amount} WEI</span>
              </li>
            ))}
          </ul>
        </section>
        <section className="contributor-section">
          <div className="contributor-title">致捐赠者：</div>
          <p className="contributor-subtitle">
            听从你内心深处的微小声音，为一个好事做出一点贡献。
          </p>
          <div className="contributor-input-container">
            {/* <span className="contributor-label">
              请输入捐款金额(不得小于100wei)
            </span> */}
            <input
              type="text"
              placeholder="请输入捐款金额(不得小于100wei)"
              className="contributor-input"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
            />
            <button onClick={Contribute} className="contributor-button">
              Submit
            </button>
          </div>
        </section>

        <section
          className="projects-section"
          style={{ display: isProjectsVisible ? "block" : "none" }}
        >
          <div className="projects-title">投票数量排行榜</div>
          <ul className="projects-list">
            {topProjects.map((project, index) => (
              <li key={index} className="project-item">
                <span>
                  {index + 1}.{" "}
                  <Link to={`/header/songwarm/${project.id}`}>
                    {project.description}: {project.votes} votes
                  </Link>
                </span>
              </li>
            ))}
          </ul>
        </section>
      </div>
    </div>
  );
};

export default Main;
